<template>
  <div 
    class="chart-item"
    :style="{ 
      left: chart.x + 'px', 
      top: chart.y + 'px', 
      width: chart.width + 'px', 
      height: chart.height + 'px',
      zIndex: zIndex
    }"
    @mousedown="bringToFront"
  >
    <!-- 图表头部 -->
    <div 
      class="chart-header"
      @mousedown="startDrag"
    >
      <span>{{ chart.title }}</span>
      <div>
        <button class="btn-secondary" @click="handleConfig">配置</button>
        <button class="btn-secondary" @click="handleDelete">删除</button>
      </div>
    </div>
    
    <!-- 图表内容 -->
    <div class="chart-content" ref="chartContent"></div>
    
    <!-- 调整大小手柄 -->
    <div 
      class="resize-handle"
      @mousedown="startResize"
    >↘</div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'ChartItem',
  props: {
    chart: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chartInstance: null,
      zIndex: 1,
      dragState: {
        isDragging: false,
        isResizing: false,
        startX: 0,
        startY: 0,
        startWidth: 0,
        startHeight: 0,
        originalX: 0,
        originalY: 0
      }
    }
  },
  mounted() {
    this.initChart()
    this.setupEventListeners()
  },
  updated() {
    this.updateChart()
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
    this.removeEventListeners()
  },
  methods: {
    // 初始化图表
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chartContent)
      this.updateChart()
    },
    
    // 更新图表
    updateChart() {
      if (!this.chartInstance) return
      
      let option = {}
    //   柱形图配置项.
      if (this.chart.type === 'bar') {
        option = {
          title: { text: this.chart.title, left: 'center' },
          xAxis: { type: 'category', data: this.chart.xAxis },
          yAxis: { type: 'value' },
          series: [{ data: this.chart.yAxis, type: 'bar' }],
          responsive: true
        }
      } else if (this.chart.type === 'line') {
        // 折线图配置项
        option = {
          title: { text: this.chart.title, left: 'center' },
          xAxis: { type: 'category', data: this.chart.xAxis },
          yAxis: { type: 'value' },
          series: [{ data: this.chart.yAxis, type: 'line', smooth: true }],
          responsive: true
        }
      } else if (this.chart.type === 'pie') {
        // 饼图配置项
        const pieData = this.chart.xAxis.map((name, i) => ({
          name,
          value: this.chart.yAxis[i]
        }))
        
        option = {
          title: { text: this.chart.title, left: 'center' },
          tooltip: { trigger: 'item' },
          series: [{ 
            name: '数据', 
            type: 'pie', 
            radius: ['40%', '70%'],
            data: pieData 
          }],
          responsive: true
        }
      }
      
      this.chartInstance.setOption(option)
    },
    
    // 置顶当前图表
    bringToFront() {
      this.zIndex = 1000
    },
    
    // 处理配置按钮
    handleConfig() {
      this.$emit('config', this.chart.id)
    },
    
    // 处理删除按钮
    handleDelete() {
      this.$emit('delete', this.chart.id)
    },
    
    // 开始拖拽
    startDrag(e) {
      e.preventDefault()
      e.stopPropagation()
      
      const rect = this.$el.getBoundingClientRect()
      
      this.dragState = {
        isDragging: true,
        isResizing: false,
        startX: e.clientX,
        startY: e.clientY,
        originalX: rect.left,
        originalY: rect.top
      }
      
      this.$el.style.cursor = 'grabbing'
      this.zIndex = 1000
    },
    
    // 开始调整大小
    startResize(e) {
      e.preventDefault()
      e.stopPropagation()
      
      const rect = this.$el.getBoundingClientRect()
      
      this.dragState = {
        isDragging: false,
        isResizing: true,
        startX: e.clientX,
        startY: e.clientY,
        startWidth: rect.width,
        startHeight: rect.height
      }
      
      this.$el.style.cursor = 'se-resize'
      this.zIndex = 1000
    },
    
    // 处理鼠标移动
    handleMouseMove(e) {
      if (!this.dragState.isDragging && !this.dragState.isResizing) return
      
      const canvasRect = this.$el.parentElement.getBoundingClientRect()
      
      if (this.dragState.isDragging) {
        // 移动图表
        const dx = e.clientX - this.dragState.startX
        const dy = e.clientY - this.dragState.startY
        
        const newX = this.dragState.originalX + dx - canvasRect.left
        const newY = this.dragState.originalY + dy - canvasRect.top
        
        this.$emit('drag', {
          chartId: this.chart.id,
          x: newX,
          y: newY
        })
      } else if (this.dragState.isResizing) {
        // 调整大小
        const dx = e.clientX - this.dragState.startX
        const dy = e.clientY - this.dragState.startY
        
        const newWidth = Math.max(200, this.dragState.startWidth + dx)
        const newHeight = Math.max(200, this.dragState.startHeight + dy)
        
        this.$emit('resize', {
          chartId: this.chart.id,
          width: newWidth,
          height: newHeight
        })
        
        // 立即更新图表大小
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
      }
    },
    
    // 处理鼠标松开
    handleMouseUp() {
      if (this.dragState.isDragging || this.dragState.isResizing) {
        this.$el.style.cursor = ''
        this.dragState = {
          isDragging: false,
          isResizing: false,
          startX: 0,
          startY: 0,
          startWidth: 0,
          startHeight: 0,
          originalX: 0,
          originalY: 0
        }
      }
    },
    
    // 设置事件监听
    setupEventListeners() {
      document.addEventListener('mousemove', this.handleMouseMove)
      document.addEventListener('mouseup', this.handleMouseUp)
      window.addEventListener('resize', this.handleWindowResize)
    },
    
    // 移除事件监听
    removeEventListeners() {
      document.removeEventListener('mousemove', this.handleMouseMove)
      document.removeEventListener('mouseup', this.handleMouseUp)
      window.removeEventListener('resize', this.handleWindowResize)
    },
    
    // 处理窗口大小变化
    handleWindowResize() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    }
  }
}
</script>

<style scoped>
.chart-item {
  position: absolute;
  min-width: 200px;
  min-height: 200px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: box-shadow 0.2s;
}

.chart-item:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.chart-header {
  background: #f5f5f5;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
}

.chart-content {
  width: 100%;
  height: calc(100% - 40px);
  padding: 10px;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 20px;
  height: 20px;
  background: #42b983;
  cursor: se-resize;
  border-radius: 0 0 8px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 12px;
}

button {
  padding: 4px 8px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 5px;
}

.btn-secondary {
  background: #ccc;
  color: #333;
}
</style>